package com.sprd.simple.launcher;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.sprd.simple.model.LauncherGridView;
import com.sprd.simple.util.KeyCodeEventUtil;
import com.sprd.simple.util.WeatherInfoUtil;
import com.sprd.simple.fragment.LauncherFragment;
import com.sprd.simple.fragment.DefaultWorkspaceFragment;
import com.sprd.simple.fragment.FamilyWorkspaceFragment;
import com.sprd.simple.fragment.FourthWorkspaceFragment;
import com.sprd.simple.fragment.ThirdWorkspaceFragment;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * Created by SPDR on 2016/7/18.
 */
public class Launcher extends FragmentActivity implements ViewPager.OnPageChangeListener {
    private static final String TAG = "Launcher";
    public static final String SOS_BROADCAST = "android.intent.action.SOS";
    private static final int sFIRST_WORKSPACE = 7;
    private static final int sDEFAULT_WORKSPACE = 1;
    private static final int sTHIRD_WORKSPACE = 1;
    private static final int sFOURTH_WORKSPACE = 2;

    private static final int PERMISSION_REQUEST = 4;
    private static final int PERMISSION_ALL_ALLOWED = 5;
    private static final int PERMISSION_ALL_DENIED = 6;
    private static final int MINI_SDK_RETURN_VALUE = -1;
    public static boolean permissionFlag = false;

    public static final String CURRENT_POSITION = "currentPosition";
    public static final String FOCUS_POSITION = "focusPosition";

    private int mCurrPosition = sDEFAULT_WORKSPACE;
    // add the control for animation
    public static boolean animAble = false;

    private Context mContext = null;
    private View mRootView;
    private ViewPager mViewPager;
    private AppSectionsPagerAdapter mAppSectionsPagerAdapter;
    private int mfocusPosition = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mContext = this;
        initView();

        if (savedInstanceState != null) {
            int currPositionTemp = savedInstanceState.getInt(CURRENT_POSITION, -1);
            int focusPositionTemp = savedInstanceState.getInt(FOCUS_POSITION, -1);
            mCurrPosition = currPositionTemp > -1 ? currPositionTemp : mCurrPosition;
            mfocusPosition = focusPositionTemp > -1 ? focusPositionTemp : mfocusPosition;
        }
    }

    private void initView() {
        setupInitRootView();
        initViewPager();
    }

    private void setupInitRootView() {
        mRootView = View.inflate(this, R.layout.activity_main, null);
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        int statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        mRootView.setPadding(0, statusBarHeight, 0, 0);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        setContentView(mRootView);
        mViewPager = (ViewPager) findViewById(R.id.pager);
    }

    public void initViewPager() {
        FragmentManager fm = getSupportFragmentManager();
        int mViewPagerId = mViewPager.getId();
        ArrayList<LauncherFragment> fragments = getFragments(mViewPagerId, fm);

        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
                fm, fragments);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);
        mViewPager.setCurrentItem(mCurrPosition);
        mViewPager.setOnPageChangeListener(this);
    }

    public ArrayList<LauncherFragment> getFragments(int viewId, FragmentManager fm) {
        ArrayList<LauncherFragment> fragments = new ArrayList<>();

        LauncherFragment familyWorkspaceFragment =
                (LauncherFragment) fm.findFragmentByTag(getFragmentTag(viewId, sFIRST_WORKSPACE));
        LauncherFragment defaultWorkspaceFragment =
                (LauncherFragment) fm.findFragmentByTag(getFragmentTag(viewId, sDEFAULT_WORKSPACE));
        LauncherFragment thirdWorkspaceFragment =
                (LauncherFragment) fm.findFragmentByTag(getFragmentTag(viewId, sTHIRD_WORKSPACE));
        LauncherFragment fourthWorkspaceFragment =
                (LauncherFragment) fm.findFragmentByTag(getFragmentTag(viewId, sFOURTH_WORKSPACE));

        if (familyWorkspaceFragment == null) {
            familyWorkspaceFragment = new FamilyWorkspaceFragment();
        }
        if (defaultWorkspaceFragment == null) {
            defaultWorkspaceFragment = new DefaultWorkspaceFragment();
        }
        if (thirdWorkspaceFragment == null) {
            thirdWorkspaceFragment = new ThirdWorkspaceFragment();
        }
        if (fourthWorkspaceFragment == null) {
            fourthWorkspaceFragment = new FourthWorkspaceFragment();
        }

        fragments.add(familyWorkspaceFragment);
        fragments.add(defaultWorkspaceFragment);
        fragments.add(thirdWorkspaceFragment);
        fragments.add(fourthWorkspaceFragment);
        for (int i = 0; i < fragments.size(); i++) {
            if (mCurrPosition == i) {
                fragments.get(i).setActived(true);
            } else {
                fragments.get(i).setActived(false);
            }
        }
        return fragments;
    }

    public String getFragmentTag(int viewId, int position) {
        try {
            Class cls = Class.forName("android.support.v4.app.FragmentPagerAdapter");
            Method method = cls.getDeclaredMethod("makeFragmentName", new Class[]{int.class, long.class});
            method.setAccessible(true);
            return (String) method.invoke(cls, viewId, position);
        } catch (ClassNotFoundException e) {
            Log.e(TAG, "ClassNotFoundException: " + e.getMessage());
        } catch (NoSuchMethodException e) {
            Log.e(TAG, "NoSuchMethodException: " + e.getMessage());
        } catch (IllegalAccessException e) {
            Log.e(TAG, "IllegalAccessException: " + e.getMessage());
        } catch (InvocationTargetException e) {
            Log.e(TAG, "InvocationTargetException: " + e.getMessage());
        }
        return null;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (Intent.ACTION_MAIN.equals(intent != null ? intent.getAction() : null)) {
            if (mViewPager != null) {
                mViewPager.setCurrentItem(sDEFAULT_WORKSPACE);
                mCurrPosition = sDEFAULT_WORKSPACE;
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(CURRENT_POSITION, mCurrPosition);
        outState.putInt(FOCUS_POSITION, mfocusPosition);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // For Permission request
        switch (checkAppPermission(this)) {
            case Launcher.PERMISSION_ALL_ALLOWED:
                Log.i(TAG, "permission allowed");
                break;

            case Launcher.PERMISSION_ALL_DENIED:
                Log.i(TAG, "permission denied");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{
                            Manifest.permission.READ_CALL_LOG,
                            Manifest.permission.READ_SMS}, PERMISSION_REQUEST);
                }
                break;

            case MINI_SDK_RETURN_VALUE:
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //add Intent for SLT
        Intent intent = new Intent("CURRENT_APP_IS_EXIT");
        sendBroadcast(intent);
        Log.d(TAG, "send broadcast for slt");
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST: {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults.length > 0) {
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            permissionFlag = false;
                            Toast.makeText(Launcher.this, R.string.unread_hint,
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            permissionFlag = true;
                        }
                    }
                }
            }
        }
    }

    private int checkAppPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean canReadCallLog = context
                    .checkSelfPermission(Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED;
            boolean canReadSMS = context
                    .checkSelfPermission(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED;
            Log.i(TAG, "canReadCallLog = " + canReadCallLog);
            Log.i(TAG, "canReadSMS = " + canReadSMS);
            if (canReadCallLog && canReadSMS) {
                return PERMISSION_ALL_ALLOWED;
            } else {
                return PERMISSION_ALL_DENIED;
            }
        } else {
            return MINI_SDK_RETURN_VALUE;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (!KeyCodeEventUtil.isLauncherNeedUseKeycode(keyCode)) {
            return false;
        }
        if (event.isTracking() && !event.isCanceled()) {
            Log.i(TAG, "onKeyUp  short press");
            switch (keyCode) {
                case KeyEvent.KEYCODE_MENU:
                    pageLeft();
                    break;
                case KeyEvent.KEYCODE_BACK:
                    pageRight();
                    break;
                default:
                    KeyCodeEventUtil.pressKeyEventForMainActivity(mContext, keyCode, event);
                    break;
            }
        } else {
            Log.i(TAG, "onKeyUp  long press");
        }
        return false;
    }

    private void pageLeft() {
        if (mViewPager != null && mCurrPosition > 0) {
            Log.i(TAG, "pageLeft");
            mViewPager.setCurrentItem(mCurrPosition - 1, true);
        }
    }

    private void pageRight() {
        if (mViewPager != null && mCurrPosition < (mViewPager.getAdapter().getCount() - 1)) {
            Log.i(TAG, "pageRight");
            mViewPager.setCurrentItem(mCurrPosition + 1, true);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!KeyCodeEventUtil.isLauncherNeedUseKeycode(keyCode)) {
            return false;
        }
        LauncherFragment currentFragment = mAppSectionsPagerAdapter.getItem(mCurrPosition);
        if (currentFragment instanceof DefaultWorkspaceFragment) {
            DefaultWorkspaceFragment defaultWorkspaceFragment = (DefaultWorkspaceFragment) currentFragment;
            LinearLayout clockView = defaultWorkspaceFragment.mClockView;
            LauncherGridView gridView = defaultWorkspaceFragment.mGridView;
            if (clockView != null && gridView != null) {
                switch (keyCode) {
                    case KeyEvent.KEYCODE_DPAD_UP:
                        if (gridView.isFocused()) {
                            gridView.clearFocus();
                            gridView.setFocusable(false);
                            clockView.requestFocus();
                            clockView.setSelected(true);
                            clockView.setNextFocusDownId(R.id.default_grid_view);
                            mfocusPosition = 0;
                            return true;
                        } else if (clockView.isSelected() || clockView.isFocused()) {
                            return false;
                        }
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        if (clockView.isSelected()) {
                            gridView.setFocusable(true);
                            gridView.requestFocus();
                            gridView.setNextFocusUpId(R.id.clock_view);
                            clockView.setSelected(false);
                            clockView.clearFocus();
                            mfocusPosition = 1;
                            LauncherFragment Lf = mAppSectionsPagerAdapter.getItem(1);
                            Lf.setActived(true);
                            if ((Lf.appNameForTTS != null) && (Lf.mGridView.isFocused())) {
                                //  TextSpeech.read(Lf.appNameForTTS[Lf.mAdapter.getSelectPosition()], mContext);
                            }
                            return true;
                        } else {
                            return false;
                        }
                    default:
                        break;
                }
            }
            //add by wpf20170104 start SPCSS00348039
        } else if (currentFragment instanceof FamilyWorkspaceFragment && keyCode == KeyEvent.KEYCODE_CALL) {
            FamilyWorkspaceFragment familyWorkspaceFragment = (FamilyWorkspaceFragment) currentFragment;
            return KeyCodeEventUtil.callFamilyItem(mContext, familyWorkspaceFragment.mFamilyAdapter.getSelectPosition());
            //add by wpf20170104 end
        }

        if (event.getRepeatCount() == 0) {
            Log.i(TAG, "getRepeatCount");
            event.startTracking();
            return true;
        }
        return false;
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {

        KeyCodeEventUtil.longPressKeyEventForMainActivity(mContext, keyCode, event);
        return true;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mCurrPosition = position;
        LauncherFragment currentFragment = mAppSectionsPagerAdapter.getItem(mCurrPosition);
        for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
            LauncherFragment Lf = mAppSectionsPagerAdapter.getItem(i);
            if (Lf != null) {
                if ((position == sDEFAULT_WORKSPACE) && (currentFragment instanceof DefaultWorkspaceFragment)) {
                    DefaultWorkspaceFragment defaultWorkspaceFragment = (DefaultWorkspaceFragment) currentFragment;
                    if (currentFragment != null) {
                        LinearLayout clockView = defaultWorkspaceFragment.mClockView;
                        LauncherGridView gridView = defaultWorkspaceFragment.mGridView;
                        if (clockView == null || gridView == null) {
                            continue;
                        }
                        if (mfocusPosition == 0) {
                            gridView.setSelected(false);
                            gridView.clearFocus();
                            clockView.setFocusable(true);
                            clockView.requestFocus();
                            clockView.setSelected(true);
                        } else if (mfocusPosition == 1) {
                            clockView.setSelected(false);
                            clockView.clearFocus();
                            gridView.setFocusable(true);
                            gridView.requestFocus();
                        }
                    }
                }

                if (i == position) {
                    Log.e(TAG, "onPageSelected [ " + i + "] setActived(true)");
                    Lf.setActived(true);
                    LauncherGridView gridView = Lf.mGridView;
                    if ((Lf.appNameForTTS != null) && (gridView != null) && (gridView.isFocused())) {
                        //  TextSpeech.read(Lf.appNameForTTS[Lf.mAdapter.getSelectPosition()], mContext);
                    }
                } else {
                    Lf.setActived(false);
                }
            }
            Log.d(TAG, "mCurrPosition = " + mCurrPosition);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the primary sections of the app.
     */
    public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<LauncherFragment> fragmentLists;

        public AppSectionsPagerAdapter(FragmentManager fm, ArrayList<LauncherFragment> fragments) {
            super(fm);
            this.fragmentLists = fragments;
        }

        @Override
        public LauncherFragment getItem(int i) {
            if (fragmentLists != null && i > -1 &&
                    i < fragmentLists.size()) {
                return fragmentLists.get(i);
            }
            return null;
        }

        @Override
        public int getCount() {
            if (fragmentLists != null) {
                return fragmentLists.size();
            }
            return 0;
        }
    }
}
